#include "SmileyTheme.h"
#include <wx/wfstream.h>
#include <wx/txtstrm.h>
#include <wx/log.h>
#include <wx/tokenzr.h>
#include <wx/regex.h>
#include "../../core/Impp.h"

namespace Impp
{

IMPLEMENT_DYNAMIC_CLASS(StdSmileyThemeManager, iModule)

SmileyTheme::SmileyTheme()
{
	wxString pixmaps = Impp::exemplar()->getPixmapsDir();
	wxString fileName = wxString::Format(wxT("%s/smileys/test.is"), pixmaps.c_str());

	wxFileInputStream stream(fileName);
	wxTextInputStream in(stream);

	int i = 0;

	while(!stream.Eof()){
		wxString line = in.ReadLine();


		if(!line.IsEmpty() && !line.StartsWith(wxT("#"))){

			wxStringTokenizer scanner(line);

			if(scanner.HasMoreTokens()){
				wxString bitmapFile = scanner.GetNextToken();
				wxString regexp;

				while ( scanner.HasMoreTokens() )
				{
				    wxString token = scanner.GetNextToken();
				    token.Replace(wxT("\\"),wxT("\\\\"));
				    token.Replace(wxT("*"),wxT("\\*"));
				    token.Replace(wxT("("),wxT("\\("));
				    token.Replace(wxT(")"),wxT("\\)"));
				    token.Replace(wxT("["),wxT("\\["));
				    token.Replace(wxT("]"),wxT("\\]"));
				    token.Replace(wxT("{"),wxT("\\{"));
				    token.Replace(wxT("}"),wxT("\\}"));
				    token.Replace(wxT("?"),wxT("\\?"));
				    token.Replace(wxT("\\\\w"),wxT(" "));

				    if(!regexp.IsEmpty()){
				    	regexp << wxT("|");
				    }
				    regexp << token;
				}

				//wxLogDebug(wxT("%i %s=%s"),i,bitmapFile.c_str(),regexp.c_str());

				Smiley smiley;
				smiley.regExp = regexp;
				smiley.bitmap = wxBitmap(wxString::Format(wxT("%s/smileys/%s"), pixmaps.c_str(), bitmapFile.c_str()) ,wxBITMAP_TYPE_ANY);


				smileys[i] = smiley;

				i++;
			}else{
				wxLogDebug(wxT("invalid entry"));
			}


		}


	}





}

SmileyTheme::~SmileyTheme()
{
}

wxString SmileyTheme::getRegExpString(){

	wxString ret;
	std::map<int,Smiley>::iterator iter = smileys.begin();

	while( iter != smileys.end() ){
		if(iter!=smileys.begin()){
			ret << wxT("|");
		}
		ret << iter->second.regExp;
		iter++;
	}

	return ret;
}

wxBitmap* SmileyTheme::getBitmap(const wxString & smiley){

	std::map<int,Smiley>::iterator iter = smileys.begin();

	while( iter != smileys.end() ){
		wxRegEx reg(iter->second.regExp,wxRE_EXTENDED|wxRE_ICASE);
		if(reg.Matches(smiley)){
			return &(iter->second.bitmap);
		}
		iter++;
	}

	return NULL;
}

}
